package com.xingu.xg.common.mapper;

import com.xingu.xg.common.entity.TreeNode;
import org.apache.ibatis.annotations.*;

import java.util.List;
@Mapper
public interface TreeNodeMapper {
    // 查询指定父节点的子节点
    @Select("SELECT * FROM tree_node WHERE parent_id = #{parentId} ORDER BY sort_order ASC")
    List<TreeNode> findByParentId(@Param("parentId") String parentId);

    // 根据路径查询子树
    @Select("SELECT * FROM tree_node WHERE path LIKE #{path} OR id = #{nodeId}")
    List<TreeNode> findByPath(@Param("path") String path, @Param("nodeId") String nodeId);

    // 插入节点
    @Insert("INSERT INTO tree_node (" +
            "id, parent_id, node_name, node_type, node_level, sort_order, " +
            "path, quantity, unit, supply_price, install_price, total_price, remark) " +
            "VALUES (" +
            "#{id}, #{parentId}, #{nodeName}, #{nodeType}, #{nodeLevel}, #{sortOrder}, " +
            "#{path}, #{quantity}, #{unit}, #{supplyPrice}, #{installPrice}, #{totalPrice}, #{remark})")
    int insert(TreeNode treeNode);

    // 更新节点
    @Update("UPDATE tree_node SET " +
            "parent_id = #{parentId}, node_name = #{nodeName}, node_type = #{nodeType}, " +
            "node_level = #{nodeLevel}, sort_order = #{sortOrder}, path = #{path}, " +
            "quantity = #{quantity}, unit = #{unit}, supply_price = #{supplyPrice}, " +
            "install_price = #{installPrice}, total_price = #{totalPrice}, remark = #{remark}, " +
            "update_time = CURRENT_TIMESTAMP WHERE id = #{id}")
    int update(TreeNode treeNode);

    // 批量更新排序
    @Update("UPDATE tree_node SET sort_order = sort_order + #{offset} " +
            "WHERE parent_id = #{parentId} AND sort_order >= #{startPos}")
    int updateSortOrder(@Param("parentId") String parentId,
                        @Param("startPos") int startPos,
                        @Param("offset") int offset);

    // 删除节点及其子树
    @Delete("DELETE FROM tree_node WHERE path LIKE #{path}")
    int deleteByPath(@Param("path") String path);

    // 根据ID查询节点
    @Select("SELECT * FROM tree_node WHERE id = #{id}")
    TreeNode findById(@Param("id") String id);
}
